!function () {
    layui.config({base: '/layui/lay/modules/'}).use(['table', 'laydate', 'dateformat','upload', 'form','status','common'], function () {
        //定义
        var $ = layui.jquery,
            table = layui.table,
            form = layui.form,
            upload = layui.upload,
            dateformat = layui.dateformat,
            laydate = layui.laydate,
            layuiSta = layui.status,//自定义状态控件
            common = layui.common;//自定义状态控件

        //启动富文本编辑
        var ueditor ;
        //定义总变量
        var Content = {
            tableId: "contentTable",    //表格id
            menuCode :"hz",           //对应菜单授权码
            menuType:{},                //类型
            condition: {                //查询条件
                name: "",
                type:"",
                startDate: "",
                endDate: ""
            },
            editorTool :null, //富文本内容
            uploadImg : null    //上传封面base64吗
        }

        /****
         * 初始化获取类别
         */
        Content.initType = function(){
            //初始化品牌类型
            Content.menuType = common.getMenuWebListByCode(Content.menuCode);
            //去除门店版图+人才合作
            $.each(Content.menuType,function(key,value){
                if( value =="门店版图" || value == '人才合作'){
                    delete Content.menuType[key];
                }
            });
            common.initMenusOptions("#typeQuery",Content.menuCode);//构建下拉选项
        }

        /**
         * 初始化列表列
         * **/
        Content.initColumn = function(){
            return [[
                /*{type: 'checkbox', fixed: 'left'},*/
                {field: 'id', title: 'ID', width: 80,hide:true},
                {field: 'title', title: '内容标题', width: 160},
               /* {field: 'url', title: '封面图片', width: 260,templet: '#imgRender'},*/
                {field: 'type' ,title :'所属类别',width:120,templet:function(row){
                        return Content.menuType[row.type]==undefined?"":Content.menuType[row.type];
                    }},
                {field: 'status' ,title :'内容显示',width:120,templet:'#statusClo'},
                {field: 'createTime' ,title :'创建时间',width: 165, templet: function (row) {
                        return dateformat.format(row.createTime, 'yyyy-MM-dd hh:mm:ss');
                    }},
                {field: 'createPerson' ,title :'创建人',width:120},
                {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 280, align: 'center'}
            ]];
        }


        /**
         * 查询方法
         * **/
        Content.search = function(){
            var queryData = {};
            queryData["name"] = $("#name").val();
            queryData["type"] = $("#typeQuery").val();
            queryData["startDate"] = $("#startDate").val();
            queryData["endDate"] = $("#endDate").val();
            table.reload(Content.tableId, {where: queryData,page: {curr: 1}});
        }

        /**
         * 新增记录
         * **/
        Content.addRecord =function (){
            window.location.href = "/content/add";
            /*//初始化表单
            $('#editForm')[0].reset();
            $('#editForm :input').val("");//重置所有的input
            //重置上传图片
            var $uploadListDiv = $('#uploadListDiv');
            var $tipUpload = $('#imgText');
            $('#uploadListDiv').empty();

            layuiSta.initStaMulti("#statusDiv",'1',true);//构建状态
            common.initMenusOptions("#type",Content.menuCode);//构建下拉选项
            layui.form.render();



            //清空富文本编辑框
            ueditor = UE.getEditor('ueditorText');
            //玄学加载
            setTimeout(function(){
                ueditor.setContent("");
            },666);
            $('#ueditorText #edui1_bottombar').hide();

            //打开弹出层
            var index = layer.open({
                type: 1, maxmin: true, title: '新增内容', shade: 0.4, shadeClose: false,
                area: ['850px', '600px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                yes: function () {
                    $('#saveRecord').click();
                }, btn2: function () {
                    layer.closeAll();
                }, end: function () {
                    $('#editForm').hide();
                }
            });
            layer.full(index);*/
        }

        /**
         * 修改记录
         * **/
        Content.editRecord =function (data){
            window.location.href = "/content/update?id="+data.id;
            //设置富文本编辑框
            /*ueditor = UE.getEditor('ueditorText');
            var $uploadListDiv = $('#uploadListDiv');
            var $tipUpload = $('#imgText');
            $('#uploadListDiv').empty();
            //初始化数据
            $.ajax({
                async: false,
                url: '/content/findContent?id=' + data.id,
                success: function (result) {
                    if (result && result.code == 200) {
                        var data = result.data;

                        //构建图片或者视频
                        var htmlDiv ='';
                        if(data.url.indexOf("image") !=-1){
                            htmlDiv +='<img id="fileDiv" src="'+data.url+'" style="height: 137px;width: 137px;"/>';
                        }
                        $uploadListDiv.empty().append(htmlDiv);
                        layuiSta.initStaMulti("#statusDiv",data.status,true);//构建状态
                        common.initMenusOptions("#type",Content.menuCode);//构建下拉选项
                        //初始化表单
                        form.render('radio').val('editForm', data);
                        if( data.contentText != undefined ) {
                            //玄学加载
                            setTimeout(function () {
                                ueditor.setContent(data.contentText);
                            }, 666);
                        }
                        $('#ueditorText #edui1_bottombar').hide();
                        //打开弹出层
                        var index = layer.open({
                            type: 1, maxmin: true, title: '修改内容', shade: 0.4, shadeClose: false,
                            area: ['850px', '600px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                            yes: function () {
                                $('#saveRecord').click();
                            }, btn2: function () {
                                layer.closeAll();
                            }, end: function () {
                                $('#editForm').hide();
                            }
                        });
                        layer.full(index);
                    }else
                        layer.alert(result.msg || '请求失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });*/
        }

        /**
         * 删除记录
         * **/
        Content.deleteRecord =function (data){
            $.ajax({
                async: false,
                type: 'post',
                url: '/content/delete?id=' + data.id,
                success: function (result) {
                    if (result && result.code == 200) {
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        Content.search();
                    }
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }

        //初始化渲染列表
        //日期
        var startDate = laydate.render({
            elem: '#startDate',
            done: function(value, date){
                endDate.config.min = date;
                endDate.config.min.month = date.month -1;
            }
        });
        var endDate =  laydate.render({
            elem: '#endDate',
            done: function(value, date){
                if($.trim(value) == ''){
                    var curDate = new Date();
                    date = {'date': curDate.getDate(), 'month': curDate.getMonth()+1, 'year': curDate.getFullYear()};
                }
                startDate.config.max = date;
                startDate.config.max.month = date.month -1;
            }
        });

        Content.initType();

        table.render({
            elem:"#contentTable"
            ,url:"/content/listPage"
            ,cellMinWidth:80
            ,request: {pageName: 'pageNum', limitName: 'pageSize'}
            ,page: true
            ,cols:Content.initColumn(),
            cellMinHeight:200

        });

        // 搜索按钮点击事件
        $('#btnSearch').click(function () {
            Content.search();
        });

        // 重置点击事件
        $('#resetSearch').click(function () {
            $('#queryTools input').val('');
            $('#queryTools select').val('');
            Content.search();
        });

        // 添加按钮点击事件
        $('#btnAdd').click(function () {
            Content.addRecord();
        });

        //普通图片上传
        var uploadFileBtn = upload.render({
            elem: '#uploadBtn'
            ,url: '/upload/uploadFiles'
            ,field:"layuiFiles"
            ,accept: 'file' //普通文件
            ,auto: false    //不自动上传
            ,exts: 'jpg|png|jpeg' //只允许上传压缩文件
            ,choose: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    var $uploadListDiv = $('#uploadListDiv');
                    var $tipUpload = $('#imgText');
                    var htmlDiv ='';
                    if(file.type.indexOf("image") !=-1){
                        if( (file.size/1014).toFixed(1) > 50 ){
                            return layer.msg("图片不能超过50kb");
                        }
                        uploadFileBtn.config.data ={"dir":"image"};
                        htmlDiv +='<img id="fileDiv" style="height: 137px;width: 137px;"/>';
                    }
                    $uploadListDiv.empty().append(htmlDiv);
                    //执行上传
                    obj.upload(index, file);
                });
            }
            ,done: function(res){
                if(res.code==1){
                    layer.alert(res.message,5);
                }
                if(res.error>0){
                    return layer.msg(res.message);
                }
                if(res.error==0){
                    var $uploadListDiv = $('#uploadListDiv');
                    $("#url").val(res.url);
                    $uploadListDiv.find("#fileDiv").attr("src",res.url);
                    layer.msg("上传成功");
                }
            }
        });

        //自定义验证规则
        form.verify({
            titleLen: [
                /^[\d\D]{1,128}$/
                ,'内容标题最多只能输入128个字'
            ],
            textLen:[
                /^[\d\D]{0,200}$/
                ,'最多输入200个字符'
            ],
        });

        //监听工具条
        table.on('tool(' + Content.tableId + ')',function(obj){
            var data = obj.data;
            var layEvent = obj.event;
            if( layEvent ==='detail'){
                //查看
                return false;
            } else if( layEvent ==='del'){
                layer.confirm('确定要删除该内容吗？', function (index) {
                    Content.deleteRecord(data);
                    return false;
                });
            } else if( layEvent ==='edit'){
                Content.editRecord(data);
                return false;
            }
        });

        //监听提交事件
        form.on('submit(editRecord)',function(data){

            //获取富文本编辑内容
            var contentText = ueditor.getContent();
            data.field['contentText']=contentText;

            //获取封面图片base64
            if( Content.uploadImg !='')
                data.field['uploadImg'] =Content.uploadImg;

            var postUrl = !data.field['id'] ? '/content/addContent' : '/content/editContent';
            $.ajax({
                async: false, type: 'post',
                traditional: true,
                data: JSON.stringify(data.field),
                contentType:"application/json;charset=UTF-8",
                processData:false,
                url: postUrl,
                success: function (data) {
                    if (data && data.code == 200) {
                        layer.closeAll();
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        Content.search();
                    } else
                        layer.alert(data.msg || '操作失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.closeAll();
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
            return false;
        });

    });
}();